package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.Bindable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.solidfire.gson.internal.LinkedTreeMap;
import com.yzp.video.view.pdf.util.Util;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.NotifyParentCheckedChanged;
import chuangyi.com.org.DOMIHome.ParagraphEditor;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.SaveContent;
import chuangyi.com.org.DOMIHome.Utils.OSSUtil;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.WaitActivityResult;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;

/**
 * Created by zxh on 16/12/5.
 */

public class ArticleEditModel extends ArticleEditorBase implements WaitActivityResult, SaveContent {

    private XListModel parent;

    public ArticleEditModel(Context context) {
        super(context);
        super.getHandler().setTitle("发文章");
    }

    public XListModel getParent() {
        return parent;
    }

    public void setParent(XListModel parent) {
        this.parent = parent;
    }

    public void load() {
        if (getId() == null)
            return;
        final Context context = getContext();
        new Thread(new Runnable() {
            @Override
            public void run() {
                LinkedTreeMap map = WebApi.getParagraphList(context, getId());
                if (map != null) {
                    ArrayList list = (ArrayList) map.get("list");
                    if (list != null && list.size() > 0) {
                        LinkedTreeMap inner = (LinkedTreeMap) list.get(0);
                        setTitle((String) inner.get("title"));
                        setLabel((String) inner.get("lable"));
                    }

                    list = (ArrayList) map.get("listcontent");
                    try {
                        if (list != null) {
                            for (Object item : list) {
                                LinkedTreeMap inner = (LinkedTreeMap) item;
                                int contentType = Utils.getIntValue(inner.get("contenttype"));
                                ParagraphItem paragraph = new ParagraphItem(getContext(), contentType);
                                paragraph.setId(Utils.getIntValue(map.get("id")));
                                paragraph.setParent(ArticleEditModel.this);
                                paragraph.setContent((String) inner.get("content"));
                                paragraph.setAllowEdit(true);
                                getParagraphs().add(paragraph);
                            }
                        }
                        notifyDataSetChanged(getParagraphs());
                    } catch (Exception ex) {
                        showToast("解析数据时发生错误");
                    }
                }
            }
        }).start();
    }

    @Override
    public void onClickPublish(View view) {
        LoadingDialog.getInstance(getContext()).show();
        if (getId() == null || getParagraphs().getCount() == 0) {
            showToast("文章内容不能为空");
            LoadingDialog.getInstance(getContext()).dismiss();
            return;
        }
        if (getTitle() == null || getTitle().equals("")) {
            showToast("标题不能为空");
            LoadingDialog.getInstance(getContext()).dismiss();
            return;
        }
        if (getLabel() == null || getLabel().equals("")) {
            showToast("标签不能为空");
            LoadingDialog.getInstance(getContext()).dismiss();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (WebApi.publishParagraph(getContext(), getId())) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Activity activity = (Activity) getContext();
                            DialogModel model = new DialogModel(activity);
                            PopupActivity.startActivityForResult(activity, R.layout.v_dialog_article_send_success,
                                    HomeActivity.REQUEST_DIALOGTIP, BR.dialogModel, model);
                        }
                    });
                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    @Override
    public void onClickSave(View view) {
        showToast("文章保存成功");
        HomeActivity.popFragment();
    }

    private void saveToDraftBox() {
        if (getContent() == null || getContent().equals("")) {
            showToast("文章内容不能为空");
            return;
        }
        if (getTitle() == null || getTitle().equals("")) {
            showToast("标题不能为空");
            return;
        }
        if (getLabel() == null || getLabel().equals("")) {
            showToast("标签不能为空");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ParagraphItem item = new ParagraphItem(getContext(), ParagraphItem.TEXT_PARAGRAPH);
                    item.setContent(getContent());
                    item.setAllowEdit(true);
                    addParagraph(item);
                } catch (Exception ex) {
                    showToast("保存文章时发生错误");
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        HomeActivity.cancelFragment();
                    }
                });
            }
        }).start();
    }

    private void notifyParent() {
        if (parent != null) {
            parent.notifyListChanged(ListBindingAdapter.ACTION_REFRESH, null);
        }
    }

    @Override
    public boolean check() {
        return true;
    }

    @Override
    public void save() {
        if (Utils.isNullOrEmpty(getContent()) && getId() == null) {
            HomeActivity.cancelFragment();
            return;
        }
        new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("确定退出编辑并保存至草稿箱吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (getId() == null) {
                            saveToDraftBox();
                        } else {
                            HomeActivity.cancelFragment();
                        }
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == HomeActivity.REQUEST_DIALOGTIP) {
            notifyParent();
            HomeActivity.cancelFragment();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
